/**
 * 网络请求工具
 * @author 王勇程 <laughskydragon@qq.com>
 */
import store from '@/store'
import { handleError, showLoading, hideLoading, checkNetworkStatus } from '@/utils/common'
import APP_CONFIG from '@/config'

// 基础配置
const BASE_URL = APP_CONFIG.BASE_URL
const API_URL = APP_CONFIG.API_URL
const TIMEOUT = APP_CONFIG.REQUEST_TIMEOUT

/**
 * 网络请求函数
 * @param {Object} options 请求配置
 */
function request(options = {}) {
  return new Promise(async (resolve, reject) => {
    // 检查网络状态
    const hasNetwork = await checkNetworkStatus()
    if (!hasNetwork) {
      reject(new Error('网络连接不可用'))
      return
    }

    // 显示加载提示
    if (options.showLoading !== false) {
      showLoading(options.loadingText || '请求中...')
    }

    // 默认配置
    const defaultOptions = {
      url: '',
      method: 'POST',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      timeout: TIMEOUT
    }

    // 合并配置
    const config = { ...defaultOptions, ...options }
    const requestPath = config.url

    if (!config.data) {
      config.data = {}
    }

    uni.$u.http.request({
      url: requestPath,
      method: config.method,
      data: config.data,
      header: config.header,
      timeout: config.timeout,
      custom: { requireAuth: options.requireAuth !== false }
    }).then((res) => {
      hideLoading()
      resolve(res)
    }).catch((error) => {
      hideLoading()
      let errorMessage = '网络请求失败'
      if (error && error.message) {
        errorMessage = error.message
      } else if (error && error.errMsg) {
        if (error.errMsg.includes('timeout')) {
          errorMessage = '请求超时，请检查网络连接'
        } else if (error.errMsg.includes('fail')) {
          errorMessage = '网络连接失败'
        } else {
          errorMessage = error.errMsg
        }
      }
      const requestError = new Error(errorMessage)
      requestError.originalError = error
      handleError(requestError, errorMessage)
      if (error && (error.code === 1000002 || error.code === 1000005)) {
        handleTokenError()
      }
      reject(requestError)
    })
  })
}

/**
 * 处理token相关错误
 * 根据API对接方案文档的错误处理机制实现
 */
function handleTokenError() {
  // 调用store中的token错误处理方法
  store.dispatch('user/handleTokenError').then(() => {
    console.log('Token错误处理完成')
  }).catch(error => {
    console.error('Token错误处理失败:', error)
    // 兜底处理：直接清除登录状态并跳转
    store.dispatch('user/logout')
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }, 1000)
  })
}

// 导出请求方法
export default request

// 便捷方法
export const GET = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'GET',
    data,
    ...options
  })
}

export const POST = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'POST',
    data,
    ...options
  })
}

export const PUT = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
    ...options
  })
}

export const DELETE = (url, data = {}, options = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
    ...options
  })
}
